package net.whippetcode.plugins.intellij.hudson.ui.job;

import net.whippetcode.plugins.intellij.hudson.domain.job.Job;
import net.whippetcode.plugins.intellij.hudson.domain.job.Workspace;
import net.whippetcode.plugins.intellij.hudson.parser.sax.SaxJobHandler;
import net.whippetcode.plugins.intellij.hudson.parser.ws.PopulateWorkspaceTask;
import net.whippetcode.plugins.intellij.hudson.util.LogUtil;
import net.whippetcode.plugins.intellij.hudson.util.XMLUtil;
import net.whippetcode.util.task.ITask;

import java.net.URL;
import java.util.logging.Level;

/**
 * This class will contact the server and load the Jobs.
 * 
 * @author David A. Freels Sr.
 */
public class PopulateJobsTask implements ITask<SaxJobHandler>
{
	private static final long serialVersionUID = -8438156983860133692L;
	
	private SaxJobHandler handler;
	private String serverAddress;
	private URL serverURL;

	public PopulateJobsTask(URL serverURL, String serverAddress)
	{
		this.serverURL = serverURL;
		this.serverAddress = serverAddress;
		this.handler = new SaxJobHandler(this.serverAddress);
	}

	public void execute()
	{
		try
		{
			XMLUtil.parseSaxContent(serverURL, handler);
		}
		catch (Exception e)
		{
			LogUtil.log(Level.SEVERE, e.getMessage(), e);
			return;
		}

		//Populate the first level of workspace.
		PopulateWorkspaceTask task;
		for (Job job : handler.getJobs())
		{
			Workspace ws = (Workspace) job.getChildren().get(0);
			task = new PopulateWorkspaceTask(this.serverAddress, job.getName() + "/ws", ws);
			task.execute();
		}
	}

	public SaxJobHandler getResult()
	{
		return handler;
	}
}
